package com.easy.work.oss;

import android.graphics.Picture;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.easy.work.app.CommonValue;
import com.easy.work.app.MyApplication;
import com.easy.work.utils.UserOssUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class PictureUpload {
    private static PictureUpload pictureUpload;
    /**
     * 上传client
     */
//    UserOssUtils   ossUtils
    OSS oss;
    /**
     * 上传次数
     */
    int number;
    /**
     * 成功上传(本地文件名作为key,阿里云地址为value)
     */
    Map<String, Object> success = new HashMap<>();
    /**
     * 失败上传(返回失败文件的本地地址)
     */
    List<String> failure = new ArrayList<>();
    /**
     * 上传回调
     */
    UploadListener uploadListener;
    /**
     * 上传任务列表
     */
    List<OSSAsyncTask> ossAsyncTasks = new ArrayList<>();

    /**
     * oss配置类
     */
    UserOssUtils ossUtils;

    /**
     * 单列模式
     *
     * @return
     */
    public static PictureUpload getInstance() {
        if (pictureUpload == null) {
            pictureUpload = new PictureUpload();
        }
        return pictureUpload;
    }

    /**
     * 构造函数
     */
    public PictureUpload() {
        ossUtils = new UserOssUtils(MyApplication.getInstance(), null);
        ossUtils.initOssData();
        oss = ossUtils.ossService.getOss();
//        ClientConfiguration conf = new ClientConfiguration();
//        conf.setConnectionTimeout(20 * 1000); // 连接超时，默认15秒
//        conf.setSocketTimeout(20 * 1000); // socket超时，默认15秒
//        conf.setMaxConcurrentRequest(9); // 最大并发请求书，默认5个
//        conf.setMaxErrorRetry(3); // 失败后最大重试次数，默认2次
//        oss = new OSSClient(MyApplication.getInstance(), HttpConfig.END_POINT, credetialProvider, conf);
    }

    /**
     * 添加上传任务
     *
     * @param paths
     * @param listener
     */
    public void setDatas(final List<String> paths, UploadListener listener) {
        this.uploadListener = listener;
        ossAsyncTasks.clear();
        number = 1;
        success.clear();
        failure.clear();
        for (String path : paths) {
            final File file = new File(path);
            /**
             * 阿里云上文件名称
             */
            String objectKey = ossUtils.getUploadUrl() + CommonValue.contractImage + number + ".jpg";
//            /**
//             * 用户自定义参数
//             */
//            ObjectMetadata objectMetadata = new ObjectMetadata();
//            objectMetadata.addUserMetadata("filePath", file.getPath());
//            objectMetadata.addUserMetadata("fileName", file.getName());
//            objectMetadata.addUserMetadata("objectKey", objectKey);


            PutObjectRequest put = new PutObjectRequest(ossUtils.getBucket(), objectKey, file.getPath());
            put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                @Override
                public void onProgress(PutObjectRequest putObjectRequest, long currentSize, long totalSize) {

                }
            });
            /**
             * 上传任务
             */
            OSSAsyncTask task;
            task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                    number++;
                    String aliPath = formAliPath(putObjectRequest);
                    success.put(putObjectRequest.getMetadata().getUserMetadata().get("fileName"), aliPath);
                    if (number == paths.size()) {
                        uploadListener.onUploadComplete(success, failure);
                    }
                }

                @Override
                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
                    number++;
                    failure.add(putObjectRequest.getMetadata().getUserMetadata().get("filePath"));
                    if (number == paths.size()) {
                        uploadListener.onUploadComplete(success, failure);
                    }
                }
            });
            /**
             * 添加到上传记录
             */
            ossAsyncTasks.add(task);
        }
    }
//
//    /**
//     * 添加上传任务
//     *
//     * @param paths    key:本地地址
//     * @param listener
//     */
//    public void setDatas(final Map<String, Picture> paths, final UploadListener listener) {
//        this.uploadListener = listener;
//        number = 1;
//        success.clear();
//        failure.clear();
//        Iterator iterator = paths.keySet().iterator();
//        while (iterator.hasNext()) {
//            final String path = (String) iterator.next();
//            final Picture picture = paths.get(path);
//            File file = new File(path);
//
//            String objectKey = UUID.randomUUID().toString() + "_" + SharePerefrence.getTokenKey() + ".jpg";
//
//            ObjectMetadata objectMetadata = new ObjectMetadata();
//            objectMetadata.addUserMetadata("fileTag", picture.getTag());
//            objectMetadata.addUserMetadata("fileName", file.getName());
//            objectMetadata.addUserMetadata("filePath", file.getPath());
//            objectMetadata.addUserMetadata("objectKey", objectKey);
//
//            final PutObjectRequest put = new PutObjectRequest(HttpConfig.BUCKET_NAME, objectKey, file.getPath());
//            put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
//                @Override
//                public void onProgress(PutObjectRequest putObjectRequest, long l, long l1) {
//                    //上传进度回调
//                }
//            });
//
//            OSSAsyncTask task;
//            task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
//                @Override
//                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
//                    number++;
//                    String aliPath = formAliPath(putObjectRequest);
//                    picture.setUrl(aliPath);
//                    picture.setName(putObjectRequest.getMetadata().getUserMetadata().get("fileName"));
//                    success.put(putObjectRequest.getMetadata().getUserMetadata().get("filePath"), picture);
//                    if (number == paths.size()) {
//                        uploadListener.onUploadComplete(success, failure);
//                    }
//                }
//
//                @Override
//                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
//                    number++;
//                    failure.add(putObjectRequest.getMetadata().getUserMetadata().get("filePath"));
//                    if (number == paths.size()) {
//                        uploadListener.onUploadComplete(success, failure);
//                    }
//                }
//            });
//            ossAsyncTasks.add(task);
//        }
//
//    }

    public void cancleTasks() {
        for (OSSAsyncTask task : ossAsyncTasks) {
            if (task.isCompleted()) {

            } else {
                task.cancel();
            }
        }
    }


    /**
     * 拼接远程访问地址
     *
     * @param putObjectRequest
     * @return
     */
    private String formAliPath(PutObjectRequest putObjectRequest) {
//        return "http://" + putObjectRequest.getBucketName() + "." + HttpConfig.END_POINT + "/" + putObjectRequest.getObjectKey();
        return ossUtils.getUploadUrl() + CommonValue.contractImage + number + ".jpg";
    }


    public interface UploadListener {
        /**
         * 上传完成
         *
         * @param success
         * @param failure
         */
        void onUploadComplete(Map<String, Object> success, List<String> failure);
    }
}